package com.xw.tools.view;

import com.xw.tools.util.Base64Util;
import javafx.event.ActionEvent;
import javafx.geometry.Insets;
import javafx.scene.Scene;
import javafx.scene.control.Button;
import javafx.scene.control.TextArea;
import javafx.scene.control.TextField;
import javafx.scene.layout.HBox;
import javafx.scene.layout.Priority;
import javafx.scene.layout.VBox;
import javafx.scene.text.Font;
import javafx.stage.FileChooser;
import javafx.stage.Stage;

import java.io.File;
import java.util.Objects;

public class FileToBase64Win extends AbstractWin {

    public void start() {
        Stage primaryStage = new Stage();
        primaryStage.setTitle("文件转base64");
        Scene scene = new Scene(new VBox(), 800, 495);
        initView(scene, primaryStage);
        primaryStage.setScene(scene);
        primaryStage.show();
    }

    private void initView(Scene scene, Stage primaryStage) {
        TextField textField = new TextField();
        Button fileBtn = new Button("请选择文件");
        TextArea outTextArea = new TextArea();
        outTextArea.setWrapText(true);
        outTextArea.setFont(Font.font(16));
        fileBtn.setOnAction((ActionEvent t) -> {
            FileChooser fileChooser = new FileChooser();
            File file = fileChooser.showOpenDialog(primaryStage);
            if (file != null && file.exists()) {
                textField.setText(file.getAbsolutePath());
            }
        });
        Button button = new Button("Encode");
        button.setOnAction((ActionEvent t) -> {
            String encode = Base64Util.encode(textField.getText());
            outTextArea.setText(Objects.toString(encode, ""));
        });
        VBox box = (VBox) scene.getRoot();
        HBox hBox = new HBox(10);
        hBox.getChildren().add(textField);
        hBox.getChildren().add(fileBtn);
        HBox.setHgrow(textField, Priority.ALWAYS);
        HBox.setHgrow(fileBtn, Priority.ALWAYS);
        box.getChildren().add(hBox);
        box.getChildren().add(button);
        VBox.setMargin(button, new Insets(10, 0, 10, 0));
        box.getChildren().add(outTextArea);
        VBox.setVgrow(outTextArea, Priority.ALWAYS);
    }

    @Override
    public void show() {
        start();
    }
}
